/*
 * \file RaceWidget.cpp
 *
 * \date Created on: Jan 21, 2009
 * \author sarah
 */

#include "RaceWidget.h"

#include <Dialogs/LoadSave.h>
#include <Dialogs/AddRace.h>
#include <Xml/XmlException.h>
#include <Xml/XmlDirectory.h>
#include <DndData/Race.h>
#include <DndData/CharacterData.h>
#include <Models/RaceModel.h>

#include <QDir>
#include <QSettings>
#include <QStringList>
#include <QDebug>
#include <QTimer>
#include <QMessageBox>

RaceWidget::RaceWidget(CharacterData *data, QWidget *parent)
    : QWidget(parent)
    , mRace(0)
    , mData(data)
{
    qDebug() << "Race widget constructor";
    mPage.setupUi(this);
    QTimer::singleShot(0, this, SLOT(updateRaceList()));
}

RaceWidget::~RaceWidget()
{
    delete mRace;
}

void RaceWidget::on_addRacePushButton_clicked(bool)
{
    XmlPath xp(XmlPath::RACIAL_BASE);
    LoadSave *openDialog = new LoadSave(xp, this);
    int result = openDialog->exec();
    if (result == QDialog::Accepted)
    {
        AddRaceDialog *addRace = new AddRaceDialog(*openDialog->path(), this);
        if (QDialog::Accepted == addRace->exec())
            updateRaceList();
    }
    delete openDialog;
}

void RaceWidget::updateRaceList()
{
    QDir raceDir;
    try {
        XmlDirectory xmlDir;
        raceDir = xmlDir.dataDir(XmlPath::RACIAL_BASE);
    }
    catch (XmlException e)
    {
        QMessageBox::warning(this, tr("Could not access race data"), e.message());
        return;
    }
    QStringList filters;
    QStringList races = raceDir.entryList(QDir::Files, QDir::Name);
    mPage.chooseRaceComboBox->clear();
    mPage.chooseRaceComboBox->addItems(races);
    if (races.size())
        mPage.chooseRaceTextLabel->setVisible(false);
}

void RaceWidget::on_chooseRaceComboBox_currentIndexChanged(const QString & index)
{
    if (index.isEmpty())
        return;
    qDebug() << "index changed to" << index;
    mRace = new Race(index);
    try {
        mRace->loadFromXml();
    }
    catch (XmlException e)
    {
        QMessageBox::warning(this, tr("Could not load race %1").arg(index), e.message());
        return;
    }
    mPage.raceDetailsTextBox->setText(mRace->raceDescription);
    mPage.chooseRaceTreeView->setModel(new RaceModel(mRace, this));
    mPage.chooseRaceTreeView->expandAll();
    int r = 0;
    for ( ; r < DndData::NUM_RACES; ++r)
        if (index == DndData::RACE_NAMES[r])
            break;
    if (r == DndData::NUM_RACES)
    {
        mData->mExtRaceName = index;
        mData->mRace = static_cast<DndData::RaceName>(0);
    }
    else
    {
        mData->mRace = static_cast<DndData::RaceName>(r);
        mData->mExtRaceName = QString();
    }
}
